﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartMap.Data.Database;
using System.Security.Cryptography;
using System.Web.Security;
using System.Web;

namespace SmartMap.Data.DataAccess
{
	public class AdminData
	{
		public static Admin Login(string username, string password)
		{
			CDataDataContext context = new CDataDataContext();
			Admin result = (from admin in context.Admins
									  where admin.AdminUserName == username
									  select admin).FirstOrDefault();
			if (result == null)
			{
				HttpContext.Current.Session["IsAuthenticated"] = null;
				return null;
			}
			string hash = CreatePasswordHash(password, result.AdminPasswordSalt);

			// IF hash matches login
			if (hash != result.AdminPasswordHash)
			{
				HttpContext.Current.Session["IsAuthenticated"] = null;
				return null;
			}
			else
			{
				HttpContext.Current.Session["IsAuthenticated"] = true;
				return result;
			}
		}

		// Hashing methods
		private static string CreateSalt(int size)
		{
			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
			byte[] buff = new byte[size];
			rng.GetBytes(buff);
			return Convert.ToBase64String(buff);
		}

		private static string CreatePasswordHash(string pwd, string salt)
		{
			string saltAndPwd = String.Concat(pwd, salt);
			string hashedPwd =
			 FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
			return hashedPwd;
		}
	}
}
